package com.boruan.qq.zxgylibrary.ui.activities;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.boruan.qq.zxgylibrary.R;
import com.boruan.qq.zxgylibrary.R2;
import com.boruan.qq.zxgylibrary.base.BaseActivity;
import com.boruan.qq.zxgylibrary.constants.ConstantInfo;
import com.boruan.qq.zxgylibrary.ui.widgets.CommonDialog;
import com.boruan.qq.zxgylibrary.utils.CallPhoneUtils;
import com.boruan.qq.zxgylibrary.utils.CustomDialog;
import com.boruan.qq.zxgylibrary.utils.NavigateUtils;
import com.boruan.qq.zxgylibrary.utils.RequestPermissionType;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by 崔琦 on 2019/8/6.
 * des: 药店首页
 */

public class PharmacyHomePageActivity extends BaseActivity {
    @BindView(R2.id.iv_pharmacy_logo)
    ImageView ivPharmacyLogo;
    @BindView(R2.id.tv_pharmacy_name)
    TextView tvPharmacyName;
    @BindView(R2.id.tv_pharmacy_support)
    TextView tvPharmacySupport;
    @BindView(R2.id.tv_pharmacy_info)
    TextView tvPharmacyInfo;
    @BindView(R2.id.ll_add_web)
    LinearLayout llAddWeb;
    @BindView(R2.id.ll_native_hide)
    LinearLayout llNativeHide;
    @BindView(R2.id.pharmacy_webView)
    WebView pharmacyWebView;

    private String shopId;
    private CustomDialog dialog;
    private String shopCid = "";
    private String skuId = "";

    @Override
    protected int getLayoutId() {
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
        return R.layout.drug_activity_pharmacy_page;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        if (getIntent() != null){
            shopId = getIntent().getStringExtra("id");
            shopCid = getIntent().getStringExtra("shopCid");
            skuId = getIntent().getStringExtra("skuid");
        }
        if (shopCid == null){
            shopCid = "";
        }
        if (skuId == null){
            skuId = "";
        }
        dialog = new CustomDialog(this,R.style.CustomDialog);
        dialog.show();
        initWeb(ConstantInfo.baseUrl + "shop?type=android&shopId=" + shopId + "&shopCid="+shopCid + "&skuId=" + skuId + "&token=" + ConstantInfo.h5UserToken);

    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void onResume() {
        super.onResume();
        if (ConstantInfo.isDetailRefresh){
            if (pharmacyWebView != null){
                //pharmacyWebView.reload();//重新刷新页面
                //不刷新页面，直接调用H5那边方法
                pharmacyWebView.evaluateJavascript("window.update()", new ValueCallback<String>() {
                    @Override
                    public void onReceiveValue(String s) {
                        Log.i("error",s);
                    }
                });
            }
            ConstantInfo.isDetailRefresh = false;
        }
    }

    @OnClick({R2.id.iv_back, R2.id.ll_search})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.iv_back) {
            finish();

        } else if (i == R.id.ll_search) {
            Intent intent = new Intent(PharmacyHomePageActivity.this, PharmacyInnerSearchActivity.class);
            startActivity(intent);

        }
    }

    /**
     * 初始化web
     */
    private void initWeb(final String richText) {

        //初始化webView
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                pharmacyWebView.getSettings().setJavaScriptEnabled(true);
                pharmacyWebView.getSettings().setSupportZoom(true);
                pharmacyWebView.getSettings().setBuiltInZoomControls(true);
                pharmacyWebView.getSettings().setDisplayZoomControls(false);
                pharmacyWebView.setVerticalScrollBarEnabled(false);

                pharmacyWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
                pharmacyWebView.getSettings().setLoadWithOverviewMode(true);
                pharmacyWebView.getSettings().setUseWideViewPort(true);
                pharmacyWebView.getSettings().setTextZoom(100);

                pharmacyWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);//默认先不使用缓存
                pharmacyWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); //取消滚动条白边效果
                pharmacyWebView.getSettings().setDefaultTextEncodingName("UTF-8");
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    pharmacyWebView.getSettings().setMixedContentMode(pharmacyWebView.getSettings().MIXED_CONTENT_ALWAYS_ALLOW);  //注意安卓5.0以上的权限
                }
                pharmacyWebView.loadUrl(richText);
                pharmacyWebView.addJavascriptInterface(PharmacyHomePageActivity.this, "control");
                pharmacyWebView.setWebViewClient(new WebViewClient(){
                    @Override
                    public void onPageStarted(WebView view, String url, Bitmap favicon) {
                        super.onPageStarted(view, url, favicon);
                        //dialog.show();
                    }

                    @Override
                    public void onPageFinished(WebView view, String url) {
                        super.onPageFinished(view, url);
                        llNativeHide.setVisibility(View.GONE);
                        dialog.dismiss();
                    }

                    @Override
                    public boolean shouldOverrideUrlLoading(WebView view, String url) {
                        view.loadUrl(url);
                        return true;
                    }

                    @Override
                    public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                        handler.proceed();//接受所有网站的证书，忽略SSL错误
                        
                    }

                    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
                    @Override
                    public void onReceivedError(WebView view, WebResourceRequest webResourceRequest, WebResourceError webResourceError) {
                        super.onReceivedError(view, webResourceRequest, webResourceError);
                        if (webResourceRequest.isForMainFrame()) {
//                            view.loadUrl("about:blank");// 避免出现默认的错误界面
//                            Toast.makeText(PharmacyHomePageActivity.this, "网络加载异常，请稍后重试！", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                        super.onReceivedError(view, errorCode, description, failingUrl);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            return;
                        }
//                        view.loadUrl("about:blank");// 避免出现默认的错误界面
//                        Toast.makeText(PharmacyHomePageActivity.this, "网络加载异常，请稍后重试！", Toast.LENGTH_SHORT).show();
                    }

                    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
                    @Override
                    public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                        super.onReceivedHttpError(view, request, errorResponse);
                        // 这个方法在 android 6.0才出现
                        int statusCode = errorResponse.getStatusCode();
                        if (404 == statusCode || 500 == statusCode) {
//                            view.loadUrl("about:blank");// 避免出现默认的错误界面
                        }
                    }
                });

            }
        }, 100);

    }

    @JavascriptInterface
    public void clickBack(){
        finish();
    }

    @JavascriptInterface
    public void clickEnterDrugDetail(String id){
        Log.i("id",id + "detail");
        Intent intent = new Intent(PharmacyHomePageActivity.this, DrugPageDetailActivity.class);
        intent.putExtra("id",id);
        intent.putExtra("shopId",shopId);
        startActivity(intent);
    }

    @JavascriptInterface
    public void clickConfirmAuthorization(final String shopName){//药店名
        //弹出用户确认授权框
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                authorizationPopWindow(shopName);
            }
        });
    }

    @JavascriptInterface
    public void clickEnterHistory(String keyWord){
        Intent intent = new Intent(PharmacyHomePageActivity.this, PharmacyInnerSearchActivity.class);
        intent.putExtra("shopId",shopId);
        intent.putExtra("keyWord",keyWord);
        startActivity(intent);
    }

    private String mobile;
    @JavascriptInterface
    public void contactMerchant(final String mPhone){
        mobile = mPhone;
        Log.i("mobile",mobile);

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                new CommonDialog.Builder(PharmacyHomePageActivity.this).setCanceledOnTouchOutside(false)
                        .setTitle("友情提示")
                        .setMessage("确定要给商家打电话吗？\n商家电话：" + mPhone)
                        .setPositiveButton("确定", new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                CallPhoneUtils.requestPermission(mPhone,PharmacyHomePageActivity.this);
                            }
                        }).setNegativeButton("取消", null).show();
            }
        });

    }


    private PopupWindow authorizationPop;
    public void authorizationPopWindow(String shopName){
        authorizationPop = new PopupWindow();
        View convertView = LayoutInflater.from(this).inflate(R.layout.drug_pop_authorization_layout,null);
        TextView tvContent = (TextView)convertView.findViewById(R.id.tv_content);
        TextView tvCancel = (TextView)convertView.findViewById(R.id.tv_cancel);
        TextView tvOk = (TextView)convertView.findViewById(R.id.tv_ok);
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                authorizationPop.dismiss();
            }
        });

        tvContent.setText(shopName + ConstantInfo.shopNotice);
        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                authorizationPop.dismiss();
                new NavigateUtils(PharmacyHomePageActivity.this).navigateConfirmOrderActivity(shopId,121);
//                Intent intent = new Intent(PharmacyHomePageActivity.this,ConfirmOrderActivity.class);
//                intent.putExtra("shopId",shopId);
//                startActivityForResult(intent,121);
                finish();
            }
        });
        authorizationPop.setContentView(convertView);

        authorizationPop.setWidth(ConstantInfo.screenWidth - 280);
        authorizationPop.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
        authorizationPop.setBackgroundDrawable(new ColorDrawable(0x00000000));
        authorizationPop.setTouchable(true);
        authorizationPop.setOutsideTouchable(false);
        /** 设置popupWindow动画 */
        authorizationPop.setAnimationStyle(R.style.style_down_to_up_animation);
        //不设置焦点的话点击外面dismiss的同时会响应外层的触摸事件
        backgroundAlpha(0.3f);
        authorizationPop.setFocusable(false);
        authorizationPop.showAtLocation(findViewById(R.id.ll_add_web), Gravity.CENTER,0,0);
        authorizationPop.setOnDismissListener(new poponDismissListener());
    }

    /**
     * 重写activity中dispatchTouchEvent,在里面判断popupWindow是否显示来决定是否往下分发事件。
     * */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if(authorizationPop != null && authorizationPop.isShowing()){
            return false;
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * PopupWindow背景变暗
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
    }

    class poponDismissListener implements PopupWindow.OnDismissListener {
        @Override
        public void onDismiss() {
            // TODO Auto-generated method stub
            backgroundAlpha(1f);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == RequestPermissionType.REQUEST_CODE_ASK_CALL_PHONE){
            for(int i=0;i<grantResults.length;i++){
                if(grantResults[i]== PackageManager.PERMISSION_GRANTED){
                    startActivity(new Intent(Intent.ACTION_CALL).setData(Uri.parse("tel:"+ mobile)));
                } else {

                }
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 121 && resultCode == 122){
            if (pharmacyWebView != null){
                //pharmacyWebView.reload();//重新刷新页面
                //不刷新页面，直接调用H5那边方法
                pharmacyWebView.evaluateJavascript("window.update()", new ValueCallback<String>() {
                    @Override
                    public void onReceiveValue(String s) {
                        Log.i("error",s);
                    }
                });
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (authorizationPop != null && authorizationPop.isShowing()){
            authorizationPop.dismiss();
            return false;
        }else {

            if (keyCode == KeyEvent.KEYCODE_BACK && pharmacyWebView.canGoBack()) {
                pharmacyWebView.goBack();
                return true;
            }
            return super.onKeyDown(keyCode, event);
        }
    }

    @Override
    protected void onDestroy() {
        if (pharmacyWebView != null) {
            //加载null内容
            pharmacyWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            //清除历史记录
            pharmacyWebView.clearHistory();
            //移除WebView
            ((ViewGroup) pharmacyWebView.getParent()).removeView(pharmacyWebView);
            //销毁VebView
            pharmacyWebView.destroy();
            //WebView置为null
            pharmacyWebView = null;
        }
        super.onDestroy();
    }


}
